import Taro from '@tarojs/taro'
import qs from 'kuan-utils/lib/qs'
import { isWx } from './validate'

/**
 * @description: 路由完整路径
 * @return: String
 */
export function fullPath() {
  // eslint-disable-next-line
  const pages = Taro.getCurrentPages() // 获取加载的页面
  const { route = '', options = {} } = pages[pages.length - 1] // 获取当前页面的对象
  let search = ''
  Object.entries(options).forEach(([key, value]) => {
    // 过滤到refresh、back
    if (['back', 'refresh'] !== key) {
      search += `&${key}=${value}`
    }
  })
  return search.substr(1) ? `/${route}?${search.substr(1)}` : `/${route}`
}

/**
 * @description: 获取小程序当前路由参数
 */
export function query() {
  // eslint-disable-next-line
  const pages = Taro.getCurrentPages() // 获取加载的页面
  const { options = {} } = pages[pages.length - 1] // 获取当前页面的对象
  return options
}

/**
 * @description: 路由跳转
 * @param {String} name 路由名字
 * @param {Object} query 路由参数
 * @param {String} action 跳转方法
 * @return: null
 */
export function to({ name = '', query = {}, action = 'navigateTo' }) {
  const route = `/pages/${name}/index`
  const search = qs.stringify(query)
  Taro[action]({
    url: search ? `${route}?${search}` : route
  })
}

/**
 * @description: 重定向登录
 */
export function redirectLogin(custom) {
  const url = fullPath()

  const name = custom || (isWx ? 'login' : 'bind')

  const isLoginPage = url.startsWith(`/pages/${name}/index`)
  if (!isLoginPage) {
    to({
      name,
      query: {
        back: encodeURIComponent(url)
      },
      action: 'redirectTo'
    })
    return Promise.reject(`redirect ${name}`)
  }
}

// 返回
export function goBack(name) {
  let pages = Taro.getCurrentPages() // 获取加载的页面
  pages = [...pages].reverse()

  const delta = pages.findIndex(item =>
    item.route.includes(`page/${name}/index`)
  )
  if (delta > 0) {
    Taro.navigateBack({
      delta
    })
  } else {
    redirectBack()
  }
}

// 重定向返回
export function redirectBack() {
  let { back } = query()
  if (back === 'undefined') back = '/pages/index/index'
  const url = back ? decodeURIComponent(back) : '/pages/index/index'
  const pages = [
    '/pages/index/index',
    '/pages/youxuan/index',
    '/pages/temai/index',
    '/pages/user/index'
  ]
  const action =
    isWx && pages.some(item => url.includes(item)) ? 'switchTab' : 'redirectTo'
  Taro[action]({
    url
  })
}
